﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

namespace Ordinaire.Commerce.VendorRelation
{
    /// <summary>
    /// Used to observe purchasing module actions.
    /// </summary>
    [Export(typeof(PurchasingObserver))]
    public class VRPurchasingObserver : PurchasingObserver
    {
        /// <summary>
        /// Builds vendor goods catalog.
        /// </summary>
        /// <param name="source">the purchasing manager</param>
        /// <param name="args">the action useful details</param>
        public override void OnAddGood(object source, Dictionary<string, object> args)
        {
            int? personId       = null;
            int? organisationId = null;

            var purchaseId        = (int) args["purchaseId"];
            var purchasingManager = (IPurchasing) source;
            purchasingManager.GetVendorIdByPurchaseId(purchaseId, out personId, out organisationId);

            // No vendor specified
            if (!personId.HasValue && !organisationId.HasValue)
            {
                return;
            }

            // Adds to vendor goods catalog
            var goodId    = (int) args["goodId"];
            var vrManager = new VendorRelationManager();
            if (personId.HasValue)
            {
                vrManager.AddPersonGoodCatalog(personId.Value, goodId);
            }
            else
            {
                vrManager.AddOrganisationGoodCatalog(organisationId.Value, goodId);
            }
        }
    }
}
